// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import mouse from "./mouse";

const {ccclass, property} = cc._decorator;

@ccclass
export class CameraController extends cc.Component {
    @property(cc.Camera)
    camera: cc.Camera = null!; // 绑定的摄像机
    @property
    minZoom: number = 0.5; // 最小缩放
    @property
    maxZoom: number = 3;   // 最大缩放
    @property
    dragSpeed: number = 0.1; // 拖动速度
    private currentZoom: number = 1;
    private lastTouchPos: cc.Vec3 | null = null;
    onLoad() {
        if (this.node.parent.getComponent(mouse).sj) {
            this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
            this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
            this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        }
    }
    private onTouchStart(event: any) {
        this.lastTouchPos = event.getLocation();
    }
    private onTouchMove(event: any) {
        let touches = event.getTouches();
        
        if (touches.length == 1) {
            // 移动摄像机
            const currentTouchPos = event.getLocation();
            if (this.lastTouchPos) {
                const delta = currentTouchPos.sub(this.lastTouchPos);
                const newPosition = this.node.position.add(delta.mul(this.dragSpeed));
                this.node.setPosition(newPosition);
            }
            this.lastTouchPos = currentTouchPos; // 更新最后触摸位置
            
        } else if (touches.length == 2) {
            // 缩放功能
            const touch1 = touches[0];
            const touch2 = touches[1];
            const touchPoint1 = this.node.parent.convertToNodeSpaceAR(touch1.getLocation());
            const touchPoint2 = this.node.parent.convertToNodeSpaceAR(touch2.getLocation());
            const distance = touchPoint1.sub(touchPoint2);
            
            // 计算缩放
            let scale = this.node.scale;
            scale += distance.length() * 0.01; // 调整缩放敏感度
            // 确保缩放在最大和最小范围内
            scale = Math.min(Math.max(scale, this.minZoom), this.maxZoom);
            this.node.scale = scale;
        }
    }
    private onTouchEnd(event: any) {
        this.lastTouchPos = null;
    }
}
